var rule_content = "",
    rule_time = "";
var deviceType = ["标杆", "标杆", "信号灯", "信号机", "太阳能", "限高杆", "标线", "护栏", "监控箱", "井盖"]
$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_ruleGroup/getRuleGroup4DT",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.content = rule_content;
                d.time = rule_time;
            }
        },
        columns: [{
            data: "ruleGroupId"
        }, {
            data: "ruleGroupType",
            render: function (data) {
                if (data == -1)
                    return "通用";
                else
                    return deviceType[data];
            }
        }, {
            data: "ruleGroupName"
        }, {
            data: "ruleGroupRemarks"
        }, {
            data: "ruleCreateTime",
            render: function (data) {
                return data.substr(0, 10)
            }
        }, {
            data: "ruleGroupId",
            render: function (data, type, row) {
                var buttonOperation = "";
                var buttonAudit = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.updateRuleGroup(" + JSON.stringify(row) + ")' title='编辑'>" +
                    "<i class='glyphicon glyphicon-check'></i></button> ";
                gCheck == 0 ? buttonOperation : buttonOperation += buttonAudit;

                buttonOperation += "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showRule(" + data + ")' title='查看'>" +
                    "<i class='glyphicon glyphicon-eye-open'></i></button> ";

                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.deleteRuleGroup(" + data + ")' title='删除'>" +
                    "<i class='fa fa-minus-square'></i></button>";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;

                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAudit = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.addRuleModel()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gCheck == 0 ? strToolBar : strToolBar += buttonAudit;

            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.deleteCover(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;

            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        }
    });

});

/*$.getOrgList=function () {
    var actorId=gUserLoginResult.userActors.indexOf("1")>0?1:2;
    var html="";
        $.ajax({
            url:"../rds_fault/getOrg4Select",
            type:"get",
            sync:false,
            data:{
                actorId:gUserLoginResult,
                orgId:gUserLoginResult.orgId
            },
            success:function (msg) {
                if(msg){
                    if(msg.isSuccess){
                        var data=msg.jsonData;
                        data.forEach(function (item) {
                            html+="<option value=''></option>"
                        })
                    }
                }
            }
        })

}*/
var redRuleDt, blueRuleDt, gUpdateModel = false;
var redCount = 0;
var blueCount = 0;
$.showRule = function (modelId) {
    gUpdateFlag = false;
    gUpdateModel = false;
    gUpdateAlias = false;
    redCount = 0;
    blueCount = 0;
    $("#modal_ruleModel").val(modelId)
    redRuleDt = $("#redRuleDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_ruleGroup/getRedRuleByModelId",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.modelId = modelId;
            }
        },
        fnPreDrawCallback:function(){
            redCount = 0;
            blueCount = 0;
        },
        columns: [{
            data: "redRuleId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox1" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: "redRuleFlag",
            render: function (data) {
                if (data == "100")
                    return "EC10" + redCount++;
                else
                    return "EC20" + blueCount++;

            }
        }, {
            data: "redRuleLevel"
        }, {
            data: "redRuleStatus"
        }, {
            data: "redRuleContent",
            render:function (data) {
                return data.split('').reverse().join('')
            }

        }, {
            data: "redRuleFlag",
            render: function (data) {
                if (data == "100")
                    return "无电";
                else
                    return "冲突";
            }
        }, {
            data: "redRuleId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' title='编辑' onclick='$.editRed(" + JSON.stringify(row) + ")'>" +
                    "<i class='glyphicon glyphicon-check'></i></button>"
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#redTool.col-md-6'>r>t<'row'<'col-md-12'>>",
        initComplete: function () {
            $("#redTool").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='redRuleDtRefresh();'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAudit = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.addRedRule()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gCheck == 0 ? strToolBar : strToolBar += buttonAudit;

            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.deleteRule(" + modelId + ",1)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;

            $("#redTool").append(strToolBar);
        },
    });

    blueRuleDt = $("#blueRuleDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_ruleGroup/getBlueRuleByModelId",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.modelId = modelId;
            }
        },
        columns: [{
            data: "blueRuleId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox2" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: "blueRuleName"
        }, {
            data: "blueRuleContent",
            render:function (data) {
                return data.split("").reverse().join("");
            }

        }, {
            data: "blueRuleFlag",
            render: function (data) {
                if (data == 0)
                    return "常亮";
                else
                    return "无电";
            }
        }, {
            data: "blueRuleId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' title='编辑' onclick='$.editBlue(" + JSON.stringify(row) + ")'>" +
                    "<i class='glyphicon glyphicon-check'></i></button>"
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#blueTool.col-md-6'>r>t<'row'<'col-md-12'p>>",
        initComplete: function () {
            $("#blueTool").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='blueRuleDtRefresh();'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAudit = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.addBlueRule()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gCheck == 0 ? strToolBar : strToolBar += buttonAudit;

            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.deleteRule(" + modelId + ",2)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;

            $("#blueTool").append(strToolBar);

        }
    });
    $("#rule-modal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

function redRuleDtRefresh() {
    redRuleDt.ajax.reload(null, false)
}

function blueRuleDtRefresh() {
    blueRuleDt.ajax.reload(null, false)
}

var gUpdateFlag, gUpdateAlias = false;
$.editRed = function (data) {
    gUpdateFlag = true;
    var content = data.redRuleStatus.split(',');
    $("#redRuleId").val(data.redRuleId);
    $("#redRuleLevel").val(data.redRuleLevel);
    $("#alarmContent").val(content[0]);
    $("#recoveryContent").val(content[1]);
    var content=data.redRuleContent.split("").reverse().join("");
    $("#redRuleContent").val(content);
    $("#redRuleFlag").val(data.redRuleFlag);
    $("#redRuleTag").val(data.redRuleTag);
    $("#red_rule_edit").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}


$.editBlue = function (data) {
    gUpdateFlag = true;
    $("#blueRuleId").val(data.blueRuleId);
    $("#blueRuleFlag").val(data.blueRuleFlag);
    $("#blueRuleLevel").val(data.blueRuleLevel);
    $("#blueRuleName").val(data.blueRuleName);
    var content=data.blueRuleContent.split("").reverse().join("");
    $("#blueRuleContent").val(content);
    $("#blue_rule_edit").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

$.checkChange1 = function () {
    var isChecked = $("#batchCheck1").prop('checked');
    $("input:checkbox[id^='checkbox1']").prop("checked", isChecked);
};
$.checkChange2 = function () {
    var isChecked = $("#batchCheck2").prop('checked');
    $("input:checkbox[id^='checkbox2']").prop("checked", isChecked);
};


$.addRedRule = function () {
    gUpdateFlag = false;
    $("#redRuleTag").val(0);
    $("#red_rule_edit").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

$.addBlueRule = function () {
    gUpdateFlag = false;
    $("#blue_rule_edit").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

$.deleteRule = function (modelId, type) {
    var count = 0, ruleIds;
    var $checkBox = $("input:checkbox[id^='checkbox" + type + "']:checked");
    count = $checkBox.length;
    if (count == 0) {
        $.alert("请选择要删除的数据", 2);
        return;
    } else {
        ruleIds = [];
        $checkBox.each(function () {
            ruleIds.push($(this).val());
        });
        count = ruleIds.length;
        ruleIds = ruleIds.join(",");
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b><br>',
        callback: function (result) {
            if (result) {
                var url = "";
                if (type == 1)
                    url = "../rds_portRule/deletePortRedRule";
                else url = "../rds_portRule/deletePortBlueRule";
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        ruleIds: ruleIds,
                        ruleModelId: modelId
                    },
                    success: function (msg) {
                        if (msg) {
                            if (msg.isSuccess) {
                                $.alert("数据删除成功", 1);
                                if (type == 2)
                                    gUpdateAlias = true;
                                else
                                    gUpdateModel = true;
                                redRuleDtRefresh();
                                blueRuleDtRefresh();
                            }
                        } else {
                            $.alert("操作失败", 2);
                        }
                    }
                })
            }
        }
    });

}

$.closeRuleModal = function () {
    if (gUpdateModel) {
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '<i class="fa fa-check"></i> 确定',
                    className: 'btn btn-primary btn-flat'
                },
                cancel: {
                    label: '<i class="fa fa-close"></i> 取消',
                    className: 'btn btn-warning btn-flat pull-left'
                }
            },
            message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">规则以有变更，是否立即更新报警器规则</b><br>',
            callback: function (result) {
                if (result) {
                    $.ajax({
                        url: "../rds_ruleGroup/updateModelRule",
                        type: "get",
                        data: {
                            ruleModelId: $("#modal_ruleModel").val()
                        },
                        success: function (msg) {
                            if (msg) {
                                if (msg.isSuccess && msg.jsonData > 0) {
                                    $.alert("更新指令已发送", 1);
                                } else {
                                    $.alert("指令发送失败，请联系管理员", 2)
                                }
                            }
                            $("#rule-modal").modal('hide')
                        }

                    })

                } else {
                    $("#rule-modal").modal('hide')
                }
            }
        })
    } else {
        if (gUpdateAlias) {
            var cmd = "0,UPDATERULE," + $("#modal_ruleModel").val();
            sendCmdFuc(cmd)
        }
        $("#rule-modal").modal('hide')

    }
}

function sendCmdFuc(cmd) {
    $.ajax({
        url: "../rds_alarmManage/sendIoCmd",
        type: 'post',
        async: false,
        data: {
            cmd: cmd,
        },
        dataType: 'json',
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    $.clearModal($('#form-cmd'), $('#modal-cmd'))
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}

function getNowTime() {
    function myDateFormat(s) {
        return s < 10 ? '0' + s : s;
    }

    var myDate = new Date();
    return myDate.getFullYear() + "-" +
        myDateFormat(myDate.getMonth() + 1) + "-" +
        myDateFormat(myDate.getDate());

}

$.updateRuleGroup = function (jsonData) {
    $("#ruleGroupId").val(jsonData.ruleGroupId)
    $("#ruleGroupType").val(jsonData.ruleGroupType)
    $("#ruleCreateTime").val(jsonData.ruleCreateTime)
    $("#ruleGroupName").val(jsonData.ruleGroupName)
    $("#ruleGroupRemarks").val(jsonData.ruleGroupRemarks)
    $("#modal-ruleGroup").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

$.addRuleModel = function () {
    $("#ruleGroupType").val(-1)
    $("#ruleCreateTime").val(getNowTime())
    $("#modal-ruleGroup").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
}

$("#redRuleFactory").click(function () {
    $("#redRuleType").val(1)
    $("#red100rule").show()
    $("#red_rule_factory").modal({
        show: true
    })
})

$("#redRuleType").change(function () {
    if ($(this).val() == 1) {
        $("#red100rule").show()
        $("#red200rule").hide()
    } else {
        $("#red100rule").hide()
        $("#red200rule").show()
    }
})

$("#saveRuleBtn").click(function () {
    var ele = "#red200rule";
    var $redRuleFlag = $("#redRuleFlag")
    $redRuleFlag.val(200)
    if ($("#redRuleType").val() == 1) {
        ele = "#red100rule";
        $redRuleFlag.val(100)
    }
    var dataList = $(ele).find("input:checked");
    var len = dataList.length;
    var sum = 0, tag = 1, num = 0;
    for (var i = 0; i < len; i++) {
        tag = 1;
        num = 8 - dataList.eq(i).val();
        tag = tag << num;
        sum += tag;
    }
    sum = parseInt(sum).toString(2) + "";
    len = 8 - sum.length;
    var result = "";
    for (var i = 0; i < len; i++)
        result += "0";
    result += sum;
    $("#redRuleContent").val(result)
    $('#red_rule_factory').modal('hide')
    $.cleanSelect()

})

$("#red_rule_factory").on("change", "#red200rule", function () {
    var dataList = $("#red200rule").find("input:checked");
    var length = dataList.length;
    if (length >= 3) {
        // $.alert("冲突规则只能设置2个端口",1);
        dataList[0].checked = false;
    }

})

$.cleanSelect = function () {
    var $red100Rule = $("#red100rule");
    var $red200Rule = $("#red200rule");
    var $red100Input = $red100Rule.find("input:checked")
    var $red200Input = $red200Rule.find("input:checked")
    for (var i = 0; i < $red100Input.length; i++) {
        $red100Input[i].checked = false
    }
    for (var i = 0; i < $red200Input.length; i++) {
        $red200Input[i].checked = false
    }

    $red100Rule.hide()
    $red200Rule.hide()

}

$("#blueRuleFactory").click(function () {
    $("#blueRuleType").val(1)
    $("#blue_rule_factory").modal({
        show: true
    })
})

$("#saveBlueRuleBtn").click(function () {
    var ele = "#blueRule";
    var $blueRuleFlag = $("#blueRuleFlag")
    var $blueRuleLevel = $("#blueRuleLevel")
    $blueRuleFlag.val(0)
    $blueRuleLevel.val(1)
    if ($("#blueRuleType").val() == 1) {
        $blueRuleFlag.val(1)
        $blueRuleLevel.val(2)
    }
    var dataList = $(ele).find("input:checked");
    var len = dataList.length;
    var sum = 0, tag = 1, num = 0;
    for (var i = 0; i < len; i++) {
        tag = 1;
        num = 8 - dataList.eq(i).val();
        tag = tag << num;
        sum += tag;
    }
    sum = parseInt(sum).toString(2) + "";
    len = 8 - sum.length;
    var result = "";
    for (var i = 0; i < len; i++)
        result += "0";
    result += sum;
    $("#blueRuleContent").val(result)
    $('#blue_rule_factory').modal('hide')
    $.cleanBlueSelect()

})

$.cleanBlueSelect = function () {
    var $input = $("#blueRule").find("input:checked");
    for (var i = 0; i < $input.length; i++) {
        $input[i].checked = false
    }
}
$('#form-ruleGroup').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        ruleGroupName: {
            validators: {
                notEmpty: {message: '规则名称不能为空'},
                stringLength: {max: 50, message: '长度不超过50'}
            }
        },
        ruleGroupRemarks: {
            validators: {
                stringLength: {max: 200, message: '长度不超过200'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var $form = $(e.target);
    var formData = $form.serialize();
    $.ajax({
        url: "../rds_ruleGroup/modifyRuleGroup",
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    gMainDT.ajax.reload(null, false);
                    $.clearModal($('#form-ruleGroup'), $('#modal-ruleGroup'))
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
    $.clearModal($("#highLeverForm"), $("#highLeverModal"));
});

$("#form-red_rule_edit").bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        redRuleLevel: {
            validators: {
                notEmpty: {message: '规则名称不能为空'},
                regexp: {regexp: /^[0-9_\.]+$/, message: '等级必须是数字'},
                stringLength: {max: 11, message: '长度不超过11'}
            }
        },
        alarmContent: {
            validators: {
                notEmpty: {message: '报警通知不能为空'},
                stringLength: {max: 15, message: '长度不超过15'}
            }
        },
        recoveryContent: {
            validators: {
                notEmpty: {message: '恢复通知不能为空'},
                stringLength: {max: 15, message: '长度不超过15'}
            }
        },
        redRuleContent2: {
            validators: {
                notEmpty: {message: '规则不能为空'},
                stringLength: {max: 8, message: '长度不超过8'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var formData = $(this).serialize();
    var url = "../rds_ruleGroup/addRedRule";
    if (gUpdateFlag)
        url = "../rds_ruleGroup/updateRedRule";

    var redRuleContent = $("#alarmContent").val() + "," + $("#recoveryContent").val()
    formData += "&RedRuleStatus=" + redRuleContent;
    formData += "&RuleModelId=" + $("#modal_ruleModel").val();
    formData += "&RedRuleMark=" + (new Date().valueOf() + "").substr(0, 10)
    formData += "&redRuleContent=" +$("#redRuleContent").val().split("").reverse().join("");
    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    $.alert("添加成功", 1);
                    if (!gUpdateFlag) {
                        gUpdateModel = true;
                    } else {
                        gUpdateAlias = true
                    }
                    redRuleDtRefresh();
                    $.clearModal($('#form-red_rule_edit'), $('#red_rule_edit'))
                } else {
                    $.alert("添加失败", 2);
                    $('#form-red_rule_edit').bootstrapValidator('disableSubmitButtons', false);
                }
            } else
                $.alert("系统异常", 2)
        }
    })
})

$("#form-blue_rule_edit").bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        blueRuleName: {
            validators: {
                notEmpty: {message: '报警提示不能为空'},
                stringLength: {max: 30, message: '长度不超过30'}
            }
        },
        blueRuleContent2: {
            validators: {
                notEmpty: {message: '规则不能为空'},
                stringLength: {max: 8, message: '长度不超过8'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var formData = $(this).serialize();
    formData += "&RuleModelId=" + $("#modal_ruleModel").val();
    formData += "&blueRuleContent=" + $("#blueRuleContent").val().split("").reverse().join("");
    var url = "../rds_ruleGroup/addBlueRule";
    if (gUpdateFlag)
        url = "../rds_ruleGroup/updateBlueRule";

    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    $.alert("添加成功", 1);
                    gUpdateAlias = true;
                    blueRuleDtRefresh();
                    $.clearModal($('#form-blue_rule_edit'), $('#blue_rule_edit'))
                } else {
                    $.alert("添加失败", 2);
                    $('#form-blue_rule_edit').bootstrapValidator('disableSubmitButtons', false);
                }
            } else
                $.alert("系统异常", 2)
        }
    })
})

$.deleteRuleGroup = function (ruleGroupId) {
    var count = 1;
    if (ruleGroupId == 0) {
        count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            $.alert("请选择要删除的数据", 2);
            return;
        } else {
            ruleGroupId = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                ruleGroupId += $(this).val() + ",";
            });
            ruleGroupId = ruleGroupId.substring(0, ruleGroupId.length - 1);
        }
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b><br><b>该操作会删除规则组对应的所有端口信息！</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_ruleGroup/deleteRuleGroupById',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "ruleGroupId": ruleGroupId
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                $.alert("数据删除成功", 1);
                                gMainDT.ajax.reload(null, false);
                            } else {
                                $.alert("数据删除失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function () {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};

$('#ruleCreateTime').datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
    todayBtn: 'linked',
    language: 'zh-CN'
});

$.fn.searchDT = function () {
    gMainDT.search().draw();
};